import React, { useEffect, useState, useMemo, useCallback } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { selectVideoAnimationById, updateVideoProperties } from '@/store/videosSlice';
import { selectStickerById, updateStickerProperties } from '@/store/stickersSlice';
import type { RootState } from '@/store';
import { Form, Select, Spin, Typography, Tabs, InputNumber, Input, Row, Col, Button } from 'antd';
import { createGlobalStyle } from 'styled-components';
import { getVideoIntroAnimations, getVideoOutroAnimations, getVideoGroupAnimations } from '@/services/project';

const { Title, Text } = Typography;
const { Option } = Select;

interface ConfigVideoAnimationFormProps {
    videoId: string;
}

// 全局 Ant Design 深色主题样式
const GlobalAntdDarkThemeStyle = createGlobalStyle`
    /* ... 基础样式（Input, Select, InputNumber 等）与之前组件相同 ... */
    /* 自定义滚动条样式 */
    .config-video-animation-scroll::-webkit-scrollbar {
        width: 3px; background: transparent;
    }
    .config-video-animation-scroll::-webkit-scrollbar-thumb {
        background: #715BB8; border-radius: 4px;
    }
    /* 表单标签 */
    .ant-form-item-label > label {
        color: #FFFFFF !important;
    }
    /* 输入/选择控件 */
    .ant-input, .ant-input-number, .ant-select-selector {
        background-color: #3C3C3C !important;
        color: #FFFFFF !important;
        border-color: #555555 !important;
    }
    .ant-input:hover, .ant-input:focus,
    .ant-input-number:hover, .ant-input-number:focus,
    .ant-select:not(.ant-select-disabled):hover .ant-select-selector {
        border-color: #888888 !important;
        box-shadow: 0 0 0 2px rgba(136, 136, 136, 0.2) !important;
    }
    .ant-input-number-handler-wrap { background-color: #3C3C3C !important; }
    .ant-input-number-handler { color: #FFFFFF !important; border-color: #555555 !important; }
    .ant-select-dropdown { background-color: #3C3C3C !important; }
    .ant-select-item-option { color: #FFFFFF !important; }
    .ant-select-item-option-selected { background-color: #555555 !important; }
    .ant-select-arrow { color: #FFFFFF !important; }

    /* **新增: Tabs 标签页样式** */
    .ant-tabs-nav {
        margin-bottom: 24px !important;
    }
    .ant-tabs-tab {
        color: #AAAAAA !important;
    }
    .ant-tabs-tab:hover {
        color: #FFFFFF !important;
    }
    .ant-tabs-tab.ant-tabs-tab-active .ant-tabs-tab-btn {
        color: #715BB8 !important;
    }
    .ant-tabs-ink-bar {
        background: #715BB8 !important;
    }
`;

const animationTypeMap = {
    intro_animations: 'Intro_type',
    outro_animations: 'Outro_type',
    group_animations: 'Group_type',
};

const tabItems = [
    { key: 'intro_animations', label: '入场动画' },
    { key: 'outro_animations', label: '出场动画' },
    { key: 'group_animations', label: '组合动画' },
];

const animationTypeNameMap: Record<string, string> = {
    Intro_type: '入场',
    Outro_type: '出场',
    Group_type: '组合',
};

const getAnimationTypeName = (type: string) => animationTypeNameMap[type] || type;

const ConfigVideoAnimationForm: React.FC<ConfigVideoAnimationFormProps> = ({ videoId }) => {
    const [form] = Form.useForm();
    const dispatch = useDispatch();

    // 判断是否为贴纸
    const isSticker = videoId?.includes('sticker') || false;

    // 根据是否为贴纸选择不同的selector
    const mediaAnimations = useSelector((state: RootState) => {
        if (!videoId) return [];
        if (isSticker) {
            const sticker = selectStickerById(state, videoId);
            return sticker?.animation || [];
        }
        return selectVideoAnimationById(state, videoId);
    });

    const [animationsData, setAnimationsData] = useState<any>({});
    const [loading, setLoading] = useState(false);
    const [activeTab, setActiveTab] = useState('intro_animations');

    const currentAnimation = useMemo(() => {
        const type = animationTypeMap[activeTab as keyof typeof animationTypeMap];
        const animations = Array.isArray(mediaAnimations) ? mediaAnimations : [];
        return animations.find((anim) => anim.animation_type === type) || null;
    }, [mediaAnimations, activeTab]);

    useEffect(() => {
        if (currentAnimation) {
            form.setFieldsValue({
                animation: currentAnimation.params,
                duration: parseFloat(currentAnimation.duration) || 1,
            });
        } else {
            form.resetFields(['animation', 'duration']);
        }
    }, [currentAnimation, form]);

    useEffect(() => {
        setLoading(true);
        Promise.all([getVideoIntroAnimations(), getVideoOutroAnimations(), getVideoGroupAnimations()])
            .then(([introRes, outroRes, groupRes]) => {
                setAnimationsData({
                    intro_animations: introRes.data?.data || [],
                    outro_animations: outroRes.data?.data || [],
                    group_animations: groupRes.data?.data || [],
                });
            })
            .catch((error) => console.error('获取视频动画数据失败:', error))
            .finally(() => setLoading(false));
    }, []);

    // 专门处理动画选择变化的方法
    const handleAnimationChange = useCallback(
        (animationValue: string) => {
            if (!videoId) return;

            const type = animationTypeMap[activeTab as keyof typeof animationTypeMap];
            const currentAnimations = Array.isArray(mediaAnimations) ? mediaAnimations : [];
            const animationIndex = currentAnimations.findIndex((anim) => anim.animation_type === type);

            let updatedAnimations;

            // 如果用户清除了动画选择，则移除该类型的动画
            if (!animationValue) {
                updatedAnimations = currentAnimations.filter((anim) => anim.animation_type !== type);
            } else {
                // 获取当前表单中的持续时间值
                const durationValue = form.getFieldValue('duration') || 1;
                const newAnimationData = {
                    animation_type: type,
                    params: animationValue,
                    duration: `${durationValue}s`,
                };
                if (animationIndex !== -1) {
                    updatedAnimations = [...currentAnimations];
                    updatedAnimations[animationIndex] = {
                        ...updatedAnimations[animationIndex],
                        ...newAnimationData,
                    };
                } else {
                    updatedAnimations = [...currentAnimations, newAnimationData];
                }
            }

            // 根据是否为贴纸调用不同的action
            if (isSticker) {
                dispatch(
                    updateStickerProperties({
                        id: videoId,
                        updates: { animation: updatedAnimations },
                    })
                );
            } else {
                dispatch(
                    updateVideoProperties({
                        id: videoId,
                        updates: { animation: updatedAnimations },
                    })
                );
            }
        },
        [videoId, activeTab, mediaAnimations, dispatch, form, isSticker]
    );

    // 专门处理持续时间变化的方法
    const handleDurationChange = useCallback(
        (durationValue: number) => {
            if (!videoId) return;

            const type = animationTypeMap[activeTab as keyof typeof animationTypeMap];
            const currentAnimations = Array.isArray(mediaAnimations) ? mediaAnimations : [];
            const animationIndex = currentAnimations.findIndex((anim) => anim.animation_type === type);
            const animationValue = form.getFieldValue('animation');

            // 只有当选择了动画时才更新持续时间
            if (animationValue && animationIndex !== -1) {
                const updatedAnimations = [...currentAnimations];
                updatedAnimations[animationIndex] = {
                    ...updatedAnimations[animationIndex],
                    duration: `${durationValue || 1}s`,
                };

                // 根据是否为贴纸调用不同的action
                if (isSticker) {
                    dispatch(
                        updateStickerProperties({
                            id: videoId,
                            updates: { animation: updatedAnimations },
                        })
                    );
                } else {
                    dispatch(
                        updateVideoProperties({
                            id: videoId,
                            updates: { animation: updatedAnimations },
                        })
                    );
                }
            }
        },
        [videoId, activeTab, mediaAnimations, dispatch, form, isSticker]
    );

    const animationsForCurrentTab = animationsData[activeTab]?.free.concat(animationsData[activeTab]?.vip) || [];

    if (!videoId) {
        return (
            <div
                style={{
                    padding: '20px',
                    color: '#FFFFFF',
                    backgroundColor: '#282828',
                    height: '100%',
                }}
            >
                未选择任何视频片段
            </div>
        );
    }

    return (
        <>
            <GlobalAntdDarkThemeStyle />
            {/* **改动1: 主容器样式与之前表单对齐** */}
            <div
                className="config-video-animation-scroll"
                style={{
                    maxHeight: 540,
                    overflowX: 'hidden',
                    overflowY: 'auto',
                    backgroundColor: '#282828',
                    color: '#FFFFFF',
                    padding: '16px',
                    borderRadius: '8px',
                }}
            >
                <Title level={4} style={{ marginBottom: 16, color: '#FFFFFF' }}>
                    属性面板
                </Title>
                <Title level={5} style={{ marginTop: 0, marginBottom: 8, color: '#FFFFFF' }}>
                    当前动画
                </Title>
                {/* **改动2: 优化当前动画显示** */}
                <div
                    style={{
                        backgroundColor: '#3C3C3C',
                        color: '#FFFFFF',
                        padding: '8px 12px',
                        borderRadius: '4px',
                        marginBottom: '16px',
                        border: '1px solid #555555',
                    }}
                >
                    <Text style={{ color: '#FFFFFF' }}>{currentAnimation ? `${getAnimationTypeName(currentAnimation.animation_type)}: ${currentAnimation.params} (${currentAnimation.duration})` : '无动画'}</Text>
                </div>

                <Tabs activeKey={activeTab} onChange={(key) => setActiveTab(key)} items={tabItems} />

                <Form form={form} layout="vertical">
                    <Row gutter={16}>
                        <Col span={12}>
                            <Form.Item label="选择动画" name="animation">
                                <Spin spinning={loading}>
                                    <Select placeholder="请选择或清除动画" allowClear onChange={handleAnimationChange}>
                                        {animationsForCurrentTab.map((anim: { name: string; display_name: React.ReactNode; is_vip: boolean }) => (
                                            <Option key={anim.name} value={anim.name}>
                                                {anim.display_name}
                                                {anim.is_vip ? ' (VIP)' : ''}
                                            </Option>
                                        ))}
                                    </Select>
                                </Spin>
                            </Form.Item>
                        </Col>
                        <Col span={12}>
                            <Form.Item label="持续时间" name="duration">
                                <InputNumber min={0.1} max={10} step={0.1} style={{ width: '95%' }} addonAfter="s" onChange={() => handleDurationChange} />
                            </Form.Item>
                        </Col>
                    </Row>
                </Form>
            </div>
        </>
    );
};
export default ConfigVideoAnimationForm;
